# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: 廖择贵
# createTime: 2021-01-12
# action: 读写Redis
from config.setting import config
import redis
import re


# redis 操作
def redis_con(key, value=None):
    re = redis.Redis(host=config.redis_host, port=config.redis_port, password=config.redis_password)
    if value:       # 如果value有值，是写入，否则是读
        re.setex(key, value, config.redis_ex_time)
    else:
        return re.get(key)


# 替换参数数据
def replace_str(res, data=None):
    it = re.finditer(config.pattern, res)
    for match in it:
        if data is not None:
            for key in data:
                if match.group(1) == key:
                    res = res.replace(match.group(), data.get(key))
        else:
            # 读取Redis查看关联参数
            re_data = redis_con(match.group(1))
            if re_data is not None:
                res = res.replace(match.group(), re_data.decode('utf-8'))
    return res


# if __name__  == '__main__':
#     # [a-zA-Z0-9]
#     res1 = '{"platform":"${user}","version":"123333","location":"${location}"}'
#     # data_dic = {"platform": "123123123","version":"1.2.25","location":"aaaaa"}
#     print(replace_str(res1))


